package day14.KeJian;

public class SellTicket01 implements Runnable{
    private int tickets = 100;
    private Object obj = new Object();
    @Override
    public void run() {
        while (true){
            synchronized (obj){
                // 对可能有安全问题的代码加锁,多个线程必须使用同一把锁
                //t1进来后，就会把这段代码给锁起来
                if (tickets>0){
                    try {
                        Thread.sleep(100);
                        //t1休息100毫秒
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //窗口1正在出售第100张票
                    System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
                    tickets--; //tickets = 99;
                }
            }
        }

    }
}
class SellTicketDemo01{
    public static void main(String[] args) {
        SellTicket01 st1 = new SellTicket01();
        Thread t1 = new Thread(st1, "窗口1");
        Thread t2 = new Thread(st1, "窗口2");
        Thread t3 = new Thread(st1, "窗口3");

        t1.start();
        t2.start();
        t3.start();

    }
}